<template>
  <div>
    <el-upload
      class="avatar-uploader"
      list-type="picture-card"
      action="#"
      :file-list="fileList"
      :class="{disable:fileList.length>0}"
      :on-remove="onRemove"
      :on-change="onChange"
      :http-request="upload"
      :before-upload="beforeUpload"
    >
      <i class="el-icon-plus avatar-uploader-icon" />
    </el-upload>
    <el-progress v-if="isShowProgress" :text-inside="true" :stroke-width="26" :percentage="percent" style="width:260px" />
  </div>

</template>

<script>
// 引入腾讯云
import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretId: 'AKID50f4C3exzlGVUDgsnRqxnMefPs40f3A1',
  SecretKey: 'cx1oKZWCbYEcjZ8PQAdoiMinb8ON5Xic'
})
export default {
  data() {
    return {
      fileList: [],
      percent: 0,
      isShowProgress: false
    }
  },
  methods: {
    onRemove(file, newFileList) {
      this.fileList = newFileList
    },
    onChange(file, newFileList) {
      this.fileList = newFileList
    },
    upload(params) {
      this.isShowProgress = true
      cos.putObject({
        Bucket: 'hr69-1308572166', /* 必须 */
        Region: 'ap-guangzhou', /* 存储桶所在地域，必须字段 */
        Key: params.file.name, /* 必须 */ // 上传到存储桶的文件名，要是变量，不能写定(‘’加引号会写定)
        StorageClass: 'STANDARD',
        Body: params.file, // 上传文件对象
        onProgress: (progressData) => {
          console.log('进度', JSON.stringify(progressData))
          // this.percent = progressData.percent * 100
          this.percent = Math.ceil(progressData.percent) * 100
        }
      }, (err, data) => {
        console.log(err || data)
        // console.log('数据', data)
        this.fileList[0].url = 'http://' + data.Location
        // console.log('图片上传', this.fileList[0])
        this.fileList[0].status = 'success'
        // 将图片的url传递给父组件addAgent
        this.$emit('imageUpload', this.fileList[0].url)
        setTimeout(() => {
          this.isShowProgress = false
        }, 1000)
      })
    },
    // 上传图片前的校验
    beforeUpload(file) {
      console.log(file)
      // 校验图片的大小
      const maxSize = 2 * 1024 * 1024 * 20
      if (file.size > maxSize) {
        this.$message.warning('图片大小不能超过2M')
        return false
      }
      // 校验图片的类型
      // 创建图片类型的白板
      const whiteList = ['image/jpeg', 'image/jpg', 'image/png']
      // 判断图片类型？？？？
      if (!whiteList.includes(file.type)) {
        this.$message.warning('图片类型不符')
        return false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.disable{
::v-deep .el-upload--picture-card{
     display: none;
 }
}
</style>
